package time.after.time.service.pro;

import java.util.List;
import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

import time.after.time.dao.pro.InfoDao;
import time.after.time.entity.pro.City;
import time.after.time.entity.pro.Info;
import time.after.time.sys.utils.Utils;

/**
 * 
 * @author HuMing create in 2013-3-27
 */
@Component
@Transactional
public class InfoManager {


	@Autowired
	private InfoDao infoDao;
	
	public void save(Info info)
	{   
		infoDao.save(info);
	}
	public List<Info> select(){
		String hql = "FROM Info WHERE userId=?";
		 List<Info> list=  infoDao.find(hql, 1);      
		return list;
	}
	public void delete(Long id){
		infoDao.delete(id);   
	}
	public List<City> selectCity(){
		String hql="FROM City WHERE grade=?";
		List<City> list=infoDao.find(hql, "PROVINCIAL");
		return list;
	}
	
	/**
	 * 信息查询
	 * 
	 * {必选字段}
	 * @param city 地址(消息源)
	 * @param afterWhen (时间查询)
	 * @param infoType (信息类型)
	 * 
	 * {搜索字段}
	 * @param column 匹配字段
	 * @param searchContent 搜索内容
	 * 
	 * 
	 */
	public List<Info> query(String citys,String afterWhen,String infoType)
	{
		List<Criterion> list=Lists.newArrayList();
		
		Criterion inCity = Restrictions.in("city",StringUtils.split(citys,","));
		
		if(StringUtils.isNotEmpty(infoType))
		{
			Criterion criterion2 = Restrictions.eq("infoType", infoType);
			list.add(criterion2);
		}
		
		Criterion timer;
		
		if(StringUtils.isEmpty(afterWhen)||!Utils.isDate(afterWhen, "yyyy-MM-dd HH:mm:ss"))
		{
			afterWhen=Utils.getNow();
		}
		
		timer= Restrictions.gt("createTime", afterWhen);
		
		/*
		if(StringUtils.isNotEmpty(column))
		{
			Criterion filter;
			if("id".equals(column))
			{
				filter=Restrictions.eq("id", NumberUtils.toLong(searchContent));
			}
			else
			{
				
				filter=Restrictions.sqlRestriction(column+" regexp '"+StringUtils.join(searchContent.split(","), "|")+"'");
			}
			list.add(filter);
		}
		*/
		
		list.add(timer);
		list.add(inCity);
		
		Criterion[] array=list.toArray(new Criterion[list.size()]);
		
		return infoDao.find(array); 
	}
}
